package com.jy.rhin.config;

import lombok.Data;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Queue;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * @author WeiQ
 * @date 2022/7/20 16:14
 * rabbitMQ 相关配置
 */
@Configuration
@EnableConfigurationProperties({RhinRabbitConfig.RhinRabbitConfigurationProperties.class})
public class RhinRabbitConfig {

    @Resource
    RhinRabbitConfigurationProperties rhinRabbitConfigurationProperties;

    /**
     * 声明聚合服务-事件总线监听MQ消息的queue
     *
     * @return
     */
    @Bean("notificationQueue")
    public Queue notificationQueue() {
        return new Queue(rhinRabbitConfigurationProperties.getNotificationQueue());
    }

    /**
     * 绑定路由：
     * 1、基础服务将需要发布给订阅者的通知发送到MQ的${exchange}交换机
     * 2、通过${publishMessageRoutingKey}key绑定
     * 3、将消息路由到聚合服务事件总线监听的队列${notificationQueue}
     *
     * @param notificationQueue
     * @return
     */
    @Bean
    public Binding binding(Queue notificationQueue) {
        return new Binding(notificationQueue.getName(),
                Binding.DestinationType.QUEUE,
                rhinRabbitConfigurationProperties.getExchange(),
                rhinRabbitConfigurationProperties.getPublishMessageRoutingKey(),
                Collections.emptyMap());
    }

    @ConfigurationProperties(prefix = "rhin.amqp.listener")
    @Data
    public static class RhinRabbitConfigurationProperties {
        /**
         * 基础服务发布MQ消息的目标交换机
         */
        private String exchange;
        /**
         * 发布【通知订阅者】消息的路由key
         */
        private String publishMessageRoutingKey;
        /**
         * 事件总线(聚合服务)监听通知事件的queue(基础服务计算得到的【需要发送给订阅者的通知】)
         */
        private String notificationQueue;
    }

}
